//
//  YxrActionView.swift
//  YXRSmartDeviceDemo
//
//  Created by run on 2024/7/3.
//

import AlertToast
import Combine
import SwiftUI

typealias ActionItemBuilder<T, V> = (T) -> V
struct YxrActionView<T, V>: View where V: View {
    let data: [T]
    let column: Int
    let hSpacing: CGFloat
    let vSpacing: CGFloat
    @ViewBuilder let itemBuilder: ActionItemBuilder<T, V>

    init(
        data: [T], column: Int = 3, hSpacing: CGFloat = 10, vSpacing: CGFloat = 10,
        itemBuilder: @escaping ActionItemBuilder<T, V>
    ) {
        self.data = data
        self.column = column
        self.hSpacing = hSpacing
        self.vSpacing = vSpacing
        self.itemBuilder = itemBuilder
    }

    var body: some View {
        VStack(alignment: .leading, spacing: hSpacing) {
            ForEach(0 ..< ((data.count + column - 1) / column), id: \.self) { row in
                HStack(spacing: hSpacing) {
                    ForEach(0 ..< min(column, data.count - row * column), id: \.self) { currentColumn in
                        itemBuilder(data[row * column + currentColumn])
                    }
                }
            }
        }
    }
}

struct YXRActionItem: View {
    let text: String
    let action: () -> Void

    var body: some View {
        Button(action: action) {
            Text(text)
                .font(.system(size: 14))
                .foregroundColor(.white)
                .padding()
                .frame(minWidth: 40, maxWidth: .infinity, minHeight: 34, maxHeight: 50)
                .background(Color.accentColor)
                .cornerRadius(10)
        }
    }
}
